package com.net;

import com.net.entity.Message;
import com.net.entity.TankJoinMessage;
import com.net.entity.TankMessageDecoder;
import com.net.entity.TankMessageEncoder;
import com.tank.entrity.Tank;
import com.tank.model.GameModel;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Client {
    public static final Client INSTANCE = new Client();
    private Channel channel = null;
    private Client() { }
    public void connection() {
        EventLoopGroup group = new NioEventLoopGroup(1);
        Bootstrap bootstrap = new Bootstrap();
        try {
            ChannelFuture future = bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            channel.pipeline()
                            .addLast(new TankMessageEncoder())
                            .addLast(new TankMessageDecoder())
                            .addLast(new SimpleChannelInboundHandler<Message>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext channelHandlerContext, Message message) throws Exception {
//                                    log.info("channel read {}", message);
                                    message.handle();
                                }

                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    ctx.writeAndFlush(new TankJoinMessage((Tank) GameModel.getInstance().getMainTank()));
                                }
                            });
                        }
                    })
                    .connect("localhost", 8888);
            future.addListener((ChannelFutureListener) channelFuture -> {
                if (channelFuture.isSuccess()) {
                    log.info("client connection is success");
                    channel = channelFuture.channel();
                } else {
                    log.error("client connection is fail");
                }
            });
            future.sync();
            future.channel().closeFuture().sync();
            log.info("client exit");
        } catch (Exception e) {
            log.error(e.getMessage());
        }finally {
            group.shutdownGracefully();
        }
    }

    public void send(Message message) {
//        log.info("send:\t" + JSON.toJSONString(message));
        channel.writeAndFlush(message);
    }
}
